import React, { useState, useEffect } from 'react';
import { Select, Spin, App } from 'antd';
import styled from 'styled-components';
import { merchantService } from '../../services';
import type { Merchant } from '../../services';
import { ShopOutlined } from '@ant-design/icons';

interface MerchantSelectorProps {
  onChange?: () => void;
}

const { Option } = Select;

const StyledSelect = styled(Select)`
  min-width: 180px;
  .ant-select-selection-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }
`;

const MerchantItem = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
`;

const MerchantSelector: React.FC<MerchantSelectorProps> = ({ onChange }) => {
  const [loading, setLoading] = useState(false);
  const [merchants, setMerchants] = useState<Merchant[]>([]);
  const [selectedMerchantId, setSelectedMerchantId] = useState<number | null>(null);
  const { message } = App.useApp();

  useEffect(() => {
    const currentId = merchantService.getMerchantId();
    setSelectedMerchantId(currentId);
    fetchMerchants();
  }, []);

  const fetchMerchants = async () => {
    try {
      setLoading(true);
      const response = await merchantService.getMerchantList();
      
      if (response.code === 0 && response.data) {
        setMerchants(response.data.list);
        
        // 如果没有选中的商户，且有商户列表，默认选择第一个
        const currentId = merchantService.getMerchantId();
        if (!currentId && response.data.list.length > 0) {
          const firstMerchant = response.data.list[0];
          handleMerchantChange(firstMerchant.id);
        }
      } else {
        message.error(response.message || '获取商户列表失败');
      }
    } catch (error) {
      console.error('获取商户列表失败:', error);
      message.error('获取商户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleMerchantChange = (value: unknown) => {
    const merchantId = value as number;
    merchantService.setMerchantId(merchantId);
    setSelectedMerchantId(merchantId);
    if (onChange) {
      onChange();
    }
  };

  return (
    <Spin spinning={loading} size="small">
      <StyledSelect
        placeholder="请选择商户"
        value={selectedMerchantId}
        onChange={handleMerchantChange}
        dropdownMatchSelectWidth={false}
        optionLabelProp="label"
      >
        {merchants.map(merchant => (
          <Option 
            key={merchant.id} 
            value={merchant.id}
            label={
              <MerchantItem>
                <ShopOutlined />
                {merchant.name}
              </MerchantItem>
            }
          >
            <MerchantItem>
              <ShopOutlined />
              {merchant.name}
            </MerchantItem>
          </Option>
        ))}
      </StyledSelect>
    </Spin>
  );
};

export default MerchantSelector; 